import jwt
from jwt import PyJWTError
from datetime import datetime,timedelta
from flask import current_app

from comment.utils import const
from comment.modules.user import User
def generate_tokens(uid):
    '''
    一个用户在一次会话中生成一个token
    :param uid:
    :return:
    '''
    params ={
        'id':uid,
        'exp':datetime.utcnow() + timedelta(seconds=const.JWT_EXPIRY_SECOND)#代表token的有效时间
    }
    #参数2  密钥  参数3  算法
    return jwt.encode(payload=params,key=const.SECRET_KEY,algorithm='HS256')


def verity_tokens(token_str):
    '''
    验证token  如果验证成功 返回用户id
    :param token_str:
    :return:
    '''
    try:
        data = jwt.decode(token_str,key=const.SECRET_KEY,algorithms='HS256')
        current_app.logger.info(data)
        user = User.query.filter(User.id == data['id']).first()
        if user and user.onlock == 0:#当前用户状态正常
            return {'id':user.id}
        else:
            return {'message':'数据库中不存在当前用户 或者用户已经过期'}
    except PyJWTError as e:
        current_app.logger.error(e)
        return {'message':'token 验证失败'}
